package com.chcit.mobile.helper;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
import android.view.View;
import android.widget.AdapterView;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.common.SPDErrorHandle;
import com.chcit.mobile.mvp.common.api.cache.CommonCache;
import com.chcit.mobile.mvp.common.api.service.CommonService;
import com.chcit.mobile.mvp.common.api.service.UserService;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.entity.UserBean;
import com.chcit.mobile.mvp.entity.WareHose;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.base.app.Quick;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class HttpClientHelper {
    private static ArrayList<WareHose> wares;
    private static UserBean user;
    private static int position;

    public static WareHose getSelectWareHouse() {
        if (wares != null) {
            return wares.get(position);
        }
        return null;
    }
    public static  void clearWares(){
        position = 0;
        wares = null;
    }
    public static void showWareSelect(Context context, MaterialDialog.ListCallbackSingleChoice callback) {
        if (wares == null) {
            wares = Quick.getConfiguration(DataKeys.WAREHOUSE_LIST);
        }
        if (Quick.getConfiguration(DataKeys.WAREHOUSE_ID) != null) {
            position = Quick.getConfiguration(DataKeys.WAREHOUSE_ID);
        }
        if (wares.size() == 1) {
            setWareHouse(context, position, callback);
        } else {
            new MaterialDialog.Builder(context)
                    .title(R.string.woreHourse)
                    .items(wares)
                    //  .itemsDisabledIndices(1, 3)
                    .autoDismiss(false)
                    .itemsCallbackSingleChoice(position
                            , (dialog, itemView, which, text) -> {
                                dialog.dismiss();
                                setWareHouse(context, which, callback);
                                return true;
                            }
                    )
                    .positiveText(R.string.ok)
                    .show();
        }

    }

    private static void setWareHouse(Context context, int which, MaterialDialog.ListCallbackSingleChoice callback) {
        JSONObject data = new JSONObject();
        data.put("warehouseId", wares.get(which).getId());
        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(context);
        appComponent.repositoryManager()
                .obtainRetrofitService(UserService.class)
                .request(HttpMethodContains.WAREHOUSE_SET_OK, data)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SPDErrorHandle<JSONObject>(appComponent.rxErrorHandler()) {

                    @Override
                    public void onNext(JSONObject result) {
                        boolean success = result.getBoolean("success");
                        if (success) {
                            position = which;
                            if (callback != null) {
                                callback.onSelection(null, null, which, wares.get(which).getName());

                            }

                        } else {
                            onError(new Exception(result.getString("msg")));
                        }

                    }

                });
    }

    public static void login() {

        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(Quick.getApplicationContext());
        appComponent.repositoryManager()
                .obtainRetrofitService(UserService.class)
                .login(user.getUsername(), user.getPassword())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SPDErrorHandle<JSONObject>(appComponent.rxErrorHandler()) {

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        if (jsonObject.getBoolean("success")) {
                            String tocken = jsonObject.getString("chcToken");
                            Quick.withConfigure(ConfigKeys.TOKEN, tocken);
                            ArmsUtils.snackbarText("已重新连接服务器，请重试！");
                        } else {
                            onError(new Exception(jsonObject.getString("msg")));
                        }

                    }

                });

    }

    public static void showWareSelect(Context context) {
        showWareSelect(context, null);
    }

    // private static  MaterialDialog materialDialog =null;
    private static Statu secondWork = null;

    public static void showSelectSecondChangeDialog(Activity context, OnSelectUserCallback callback) {

        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(context);
        // if(materialDialog == null||!(materialDialog.getContext() instanceof Activity)) {
        MaterialDialog materialDialog = new MaterialDialog.Builder(context)
                .title("选择第二作业人")
                .customView(R.layout.dialog_input_passowrd, true)
                //  .itemsDisabledIndices(1, 3)
                .autoDismiss(false)
                .cancelable(false)
                .negativeText(R.string.cancel)
                .positiveText(R.string.ok)
                .onNegative((dialog, which) -> {
                    dialog.dismiss();
                    secondWork = null;
                })
                .onPositive((dialog, which) -> {
                    AppCompatEditText etPassWord = dialog.getCustomView().findViewById(R.id.et_input_password);
                    String password = null;
                    if (etPassWord.getText() == null || etPassWord.getText().toString().isEmpty()) {
                        DialogUtil.showMsgDialog(context, "密码不能为空！");
                        return;
                    }
                    password = etPassWord.getText().toString();
                    appComponent.repositoryManager()
                            .obtainRetrofitService(CommonService.class)
                            .checkUser(secondWork.getId(), password)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new SPDErrorHandle<String>(appComponent.rxErrorHandler()) {
                                @Override
                                public void onNext(String resultBean) {
                                    JSONObject jsonObject = JSONObject.parseObject(resultBean);
                                    if (jsonObject.getBoolean("success")) {
                                        callback.onInput(dialog, secondWork);
                                        dialog.dismiss();
                                    } else {
                                        String msg = jsonObject.getString("msg");
                                        onError(new Exception(msg == null ? "未知错误！" : msg));
                                    }
                                }

                                @Override
                                public void onError(Throwable t) {
                                    DialogUtil.showMsgDialog(context, t.getMessage());
                                }
                            });

                })
                .build();
        //etPassWord = materialDialog.getCustomView().findViewById(R.id.et_input_password);

        //}
        /*readWrite:Y
        excludeSelf:Y
        userType:2
        warehouseId:1000214*/
        queryUsers(appComponent, materialDialog);

    }

    public interface OnSelectUserCallback {

        void onInput(@NonNull MaterialDialog dialog, Statu user);
    }

    private static void queryUsers(AppComponent appComponent, MaterialDialog materialDialog) {
        JSONObject data = new JSONObject();
        data.put("readWrite", "Y");
        data.put("excludeSelf", "Y");
        data.put("userType", 2);
        data.put("warehouseId", getSelectWareHouse().getId());
        Observable.just(appComponent.repositoryManager()
                .obtainRetrofitService(CommonService.class)
                .queryUsers(data).map(baseData -> {
                    if (baseData.isSuccess()) {
                        if (baseData.getTotal() > 0)
                            return baseData.getRows();
                        throw new Exception("没有查询到负责人");
                    } else {
                        String msg = baseData.getMsg();
                        throw new Exception(msg == null ? "未知错误" : msg);
                    }
                }))
                .flatMap((Function<Observable<List<Statu>>, ObservableSource<List<Statu>>>) stringObservable -> appComponent.repositoryManager()
                        .obtainCacheService(CommonCache.class)
                        .queryUsers(stringObservable))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SPDErrorHandle<List<Statu>>(appComponent.rxErrorHandler()) {
                    @Override
                    public void onNext(List<Statu> result) {

                        EditSpinner spinner = materialDialog.getCustomView().<EditSpinner>findViewById(R.id.spinner_input_username);
                        secondWork = result.get(0);
                        spinner.setItemData(result);
                        spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (position > 0 && result.size() > position) {
                                    secondWork = result.get(position);
                                }
                            }
                        });
                        spinner.setText(secondWork.getName());
                        materialDialog.show();


                    }
                });
    }

    public static void showMsgDialog(final Context ctx, String title, String msg) {

        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);

        builder.setMessage(msg);
        builder.setTitle(title);

        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public static String getUserName() {
        return user.getUsername();
    }

    public static void setUserName(String userName) {
        HttpClientHelper.user.setUsername(userName);
    }

    public static String getPassword() {
        return user.getPassword();
    }

    public static void setPassword(String password) {
        HttpClientHelper.user.setPassword(password);
    }

    public static void setUser(UserBean user) {
        HttpClientHelper.user = user;
    }
    public static UserBean getSystemUser() {
        return user;
    }
    //第二收货人
    public static Statu getUser() {
        return secondWork;
    }
}
